package com.citycloud.ccuap.tc.admin.engine;

import com.citycloud.ccuap.commons.application.Application;
import com.citycloud.ccuap.commons.engine.base.AbstractEngine;
import com.citycloud.ccuap.commons.engine.base.IEngine;
import com.citycloud.ccuap.framework.service.mybatis.ICommonService;
import com.citycloud.ccuap.tc.admin.dbupdate.IDbUpdateService;
import com.citycloud.ccuap.tc.admin.entity.SysDbUpdate;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class DbUpdateEngine extends AbstractEngine implements IEngine {
    private static DbUpdateEngine instance;

    private DbUpdateEngine(String profile) {
    }

    public static DbUpdateEngine getInstance(String profile) {
        if (instance == null) {
            instance = new DbUpdateEngine(profile);
        }
        return instance;
    }

    @Override
    public void initialize(String profile) {
        try {
            IDbUpdateService dbUpdateService = Application.getServiceByBeanName("dbUpdateService");
            List<SysDbUpdate> list = dbUpdateService.selectList();
            List<String> fileList = list.stream().map(SysDbUpdate::getSqlName).collect(Collectors.toList());

            Resource[] resources = new PathMatchingResourcePatternResolver().getResources("database/*.sql");
            for (Resource resource : resources) {
                if (!fileList.contains(resource.getFilename())) {
                    InputStream inputStream = resource.getInputStream();
                    String sqlString = IOUtils.toString(inputStream, "UTF-8");

                    execSqlFile(sqlString);

                    SysDbUpdate sysDbUpdate = new SysDbUpdate();
                    sysDbUpdate.setSqlName(resource.getFilename());
                    sysDbUpdate.setSqlContent(sqlString);
                    sysDbUpdate.setExecuteTime(new Date());
                    dbUpdateService.insert(sysDbUpdate);
                }
            }
        } catch (Exception ex) {
            logger.error("=============## DbUpdateEngine 加载失败！=============");
            ex.printStackTrace();
        }

        logger.info("=============## DbUpdateEngine 加载成功##================");
    }

    @Override
    public void destroy(String profile) {
        logger.info("=============## DbUpdateEngine 销毁##================");
    }

    public void execSqlFile(String sqlString) throws Exception {
        ICommonService commonService = Application.getServiceByBeanName("commonService");

        String[] sqls = sqlString.split(";");
        List<String> sqlList = new ArrayList<>();
        if (sqls != null) {
            for (int i = 0; i < sqls.length; i++) {
                String sql = sqls[i].replace("\n", "");
                if (!"".equals(sql)) {
                    sqlList.add(sql);
                }
            }
            String[] destSqls = new String[sqlList.size()];
            commonService.executeSqls(sqlList.toArray(destSqls));
        }
    }
}
